import {Message} from 'element-ui';


let websock = null;
let messageCallback = null;
let errorCallback = null;

let wsUrl = '';
//let tryTime = 0;

//接收websocket后端数据.
function websocketonmessage (e) {
    //messageCallback(JSON.parse(e.data));
    messageCallback(e.data);
}

/**
 * 发起websocket连接
 */
function websocketSend (agentData) {
    setTimeout( () => {
        if(websock.readyState === websock.OPEN) {
            websock.send(JSON.stringify(agentData))
        }
        if(websock.readyState === websock.CLOSED) {
            console.log('websock.readyState = 3');
            Message.error('ws连接异常，请稍后再试');
            errorCallback();
        }
    }, 500)
}

//关闭ws连接.
function websocketClose(e) {
    if(e && e.code !== 1000) {
        Message.error('ws连接异常，请稍后再试');
        errorCallback()
    }
}

//建立ws连接.
function websocketOpen() {
    console.log('ws连接成功');
}

//初始化websocket.
function initWebSocket () {
    if(typeof(WebSocket) === 'undefined') {
        Message.error('浏览器不支持Websocket，无法获取数据');
        return false;
    }

    //ws请求完整地址.
    const requstWsUrl = wsUrl;
    websock = new WebSocket(requstWsUrl);

    websock.onmessage = function (e) {
        websocketonmessage(e);
    }
    websock.onopen = function () {
        websocketOpen();
    }
    websock.onerror = function () {
        Message.error('ws连接异常，请稍后再试');
        errorCallback();
    }
    websock.onclose = function (e) {
        websocketClose(e);
    }
}


export function sendWebsocket (url, agentData, successCallback, errCallback) {
    wsUrl = url;
    initWebSocket();
    messageCallback = successCallback;
    errorCallback = errCallback;
    websocketSend(agentData);
}

export function recvWebsocket (url, successCallback, errCallback) {
    wsUrl = url;
    initWebSocket();
    messageCallback = successCallback;
    errorCallback = errCallback;
}

export function closeWebsocket () {
    if (websock) {
        websock.close();
        websock.onclose();
    }
}
